package com.xczl.book.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.shishuo.cms.entity.vo.PageVo;
import com.xczl.book.dao.BorrowDao;
import com.xczl.book.entity.Borrow;
import com.xczl.book.entity.vo.BorrowVo;

@Service
@Transactional
public class BorrowService {

	@Autowired
	private BorrowDao borrowDao;

	@Autowired
	private BookService bookService;
	/**
	 * 添加图书
	 * 
	 * @param borrow
	 */
	public void add(Borrow borrow) {
		// 实体是否存在
		Assert.notNull(borrow);
		Assert.notNull(borrow.getBookId(), "请填写图书ID");
		Assert.notNull(borrow.getUserId(), "请填写用户ID");
		Assert.notNull(borrow.getBorrowTime(), "请填写借阅时间");
		long returnTime = borrow.getBorrowTime().getTime()
				+ Borrow.BORROW_LIMIT;
		borrow.setReturnTime(new Date(returnTime));
		/**
		 * 判断是否借出
		 */
		if(borrow.getState()==Borrow.STATE_ING){
			bookService.editLibrarieNumber(borrow.getBookId(),-1);
		}
		// Dao插入数据
		borrowDao.insertBorrow(borrow);
	}

	/**
	 * 修改图书
	 * 
	 * @param borrow
	 */
	public void update(int id, int state) {
		// Dao导入数据
		borrowDao.updateStateById(id, state);
	}

	/**
	 * 根据id查询
	 * 
	 * @return
	 */
	public Borrow findById(int id) {
		return borrowDao.findById(id);
	}

	/**
	 * 全部
	 * 
	 * @return
	 */
	public PageVo<BorrowVo> findByCondition(int pageNum, BorrowVo filter) {
		PageVo<BorrowVo> pageVo = new PageVo<BorrowVo>(pageNum);// 创建翻页对象
		pageVo.setRows(10);
		List<BorrowVo> list = borrowDao.findByCondition(filter,
				pageVo.getOffset(), pageVo.getRows());// 翻页查询
		int count = borrowDao.findCountBySearch(filter);// 查询总记录数
		pageVo.setList(list);// 设置内容
		pageVo.setCount(count);// 设置总记录数
		return pageVo;
	}

	public void batchBorrow(int userId, int[] bookIds) {
		Borrow borrow = null;
		Date borrowTime = new Date();
		for (int bookId : bookIds) {
			borrow = new Borrow();
			borrow.setBookId(bookId);
			borrow.setUserId(userId);
			borrow.setBorrowTime(borrowTime);
			borrow.setState(Borrow.STATE_ING);
			add(borrow);
		}
	}
}
